package com.smarthouse.controller;

import com.alibaba.fastjson2.JSON;
import com.smarthouse.model.ApiResponse;
import com.smarthouse.model.LoginRequest;
import com.smarthouse.model.LoginResponse;
import com.smarthouse.service.UserAccountService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

@Tag(name = "认证接口")
@RestController
@RequestMapping("/auth")
@CrossOrigin
public class AuthController {
    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private UserAccountService userAccountService;

    @Operation(summary = "用户登录")
    @PostMapping(value = "/login", produces = MediaType.APPLICATION_JSON_VALUE)
    public String login(@RequestBody LoginRequest request) {
        logger.info("收到登录请求");
        
        try {
            // 参数校验
            if (request == null) {
                logger.error("登录请求体为空");
                return JSON.toJSONString(ApiResponse.error("请求参数不能为空"));
            }
            
            if (request.getUsername() == null || request.getUsername().trim().isEmpty()) {
                logger.error("用户名为空");
                return JSON.toJSONString(ApiResponse.error("用户名不能为空"));
            }
            
            if (request.getPassword() == null || request.getPassword().trim().isEmpty()) {
                logger.error("密码为空");
                return JSON.toJSONString(ApiResponse.error("密码不能为空"));
            }

            // 调用服务层处理登录
            String token = userAccountService.login(request.getUsername(), request.getPassword());
            LoginResponse loginResponse = new LoginResponse(token, "登录成功");
            logger.info("用户 {} 登录成功", request.getUsername());
            return JSON.toJSONString(ApiResponse.success(loginResponse));
            
        } catch (Exception e) {
            logger.error("登录失败: {}", e.getMessage(), e);
            return JSON.toJSONString(ApiResponse.error(e.getMessage()));
        }
    }
} 